<?php

class RegisterController extends Front_Libraries_Controller_Public
{

    public function indexAction()
    {
        if(Zend_Auth::getInstance()->hasIdentity()) {
            $this->_redirect('/front/index');
        }
        
        $request = $this->_request;
        $registerForm = new Front_Form_Register();
        
        if($request->isPost()) {
            if($registerForm->isValid($request->getPost())) {
                $department = $this->_em->getRepository('Entities\Department')->find($request->getParam('department'));
                if (null === $department){ //hackin here
                    $this->_redirect('front');
                }

                $contact = new Entities\User();
                $contact->setUsername($request->getParam('username'));
                $contact->encryptPassword($request->getParam('password'));
                $contact->setName($request->getParam('name'));
                $contact->setMobilephone($request->getParam('mobile'));
                $contact->setEmail($request->getParam('email'));
                $contact->setDepartment($department);
                //information to active username
                $time = time();
                $contact->generateToken($time);
                $contact->setPasswordRequestAt($time);
                
                //sendmail
                $this->sendMail(
                        $contact->getEmail(), 
                        'Sutrix Drink - Register',
                        $this->messageMailRegister($contact->getToken(), $contact->getUsername())
                        );
                
                //save object
                $this->_em->persist($contact);
                $this->_em->flush();

                
                $this->view->message = "Congratulation, your register is successfull. Check your email to active your acconut.";
                $this->render('message'); 
            }
        }

        $this->view->registerForm = $registerForm; 
    
    }
    
    public function activeAction()
    {
        $request = $this->_request;
        
        //get email
        $username = $request->getParam('username', '');
        $token = $request->getParam('token', '');
        
        //find contact with the email
        $contact = $this->_em->getRepository('Entities\User')->findOneBy(array('username'=>$username));

        if (null === $contact) {
            $this->_redirect('front');
        } else {
            if ($token == $contact->getToken()) {
                //update some value of contact
                $contact->setActive(1);
                $contact->setToken(null);
                $contact->setPasswordRequestAt(null);
                //save contact
                $this->_em->flush();
                
                $this->view->message = "Congratulation, your account is actived.";
            } else {
                $this->_redirect('front');
            }
        }
    }
    
    public function resetAction()
    {
        $request = $this->_request;
        $resetForm = new Front_Form_ResetRequire();
        $message = "";
        
        if($request->isPost()) {
            if($resetForm->isValid($request->getPost())) {
                $email = $request->getParam('email', '');
                $username = $request->getParam('username', '');
                $contact = $this->_em->getRepository('Entities\User')->findOneBy(array('username'=>$username, 'email'=>$email));
                if (null === $contact) {
                    $message = "Your username or account is not correct!";
                } else {
                    $time = time();
                    $_send = false;
                    $requestAt = $contact->getPasswordRequestAt();
                    if (empty($requestAt)) {
                        $_send = true;
                    } else {
                        if (($time - $requestAt) < (60 * 60 * 24) ) {
                            $message = "The password for this user has already been requested within the last 24 hours.";
                        } else {
                            $_send = true;
                        }
                    }
                    if ($_send){
                        $contact->setPasswordRequestAt($time);
                        $contact->generateToken($time);
                        //save contact
                        $this->_em->flush();
                        //sendmail
                        $this->sendMail(
                            $contact->getEmail(), 
                            'Sutrix Drink - Reset Password',
                            $this->messageMailReset($contact->getToken(), $contact->getUsername())
                        );
                        $this->_redirect('front/login/index/message/' . urlencode('An email has been sent to you. It contains a link you must click to reset your password'));
                    }
                }
            }
        }
        $this->view->message = $message;
        $this->view->resetForm = $resetForm; 
    }
    
    public function changeAction()
    {
        $request = $this->_request;

        $username = $request->getParam('username', '');
        $token = $request->getParam('token', '');
        
        //find contact with the email
        $contact = $this->_em->getRepository('Entities\User')->findOneBy(array('username'=>$username));

        if (null === $contact) {
            $this->_redirect('front');
        } else {
            if ($token == $contact->getToken()) {
                $resetForm = new Front_Form_ResetPassword();
                $resetForm->setAction($this->getRequest()->getRequestUri());
                $resetForm->populate(array(
                    'id'=>$contact->getId(),
                    ));
                $message = "";
                
                if($request->isPost()) {
                    if($resetForm->isValid($request->getPost())) {
                        $id = (int)$request->getParam('id', '');
                        $password = $request->getParam('password', '');

                        if ( $contact->getId() == $id ) {
                            $contact->encryptPassword($password);
                            $contact->setPasswordRequestAt(null);
                            $contact->setToken(null);
                            //save contact
                            $this->_em->flush();
                            
                            $this->_redirect('front/login/index/message/' . urlencode('Your password has been changed. Login with new password.'));
                        } else {
                            $message = "Something wrong";
                        }

                    }
                }
                
                $this->view->resetForm = $resetForm;
            } else {
                $this->_redirect('front');
            }
        }
        $this->view->message = $message;
    }

    private function messageMailRegister($token, $username)
    {
        $url = $this->_helper->url->url(array(
            'module' => 'front',
            'controller'=>'register',
            'action'=>'active',
            'username'=>$username,
            'token'=>$token
            ));

        $this->view->name = $username;
        $this->view->activeLink = $url;
        
        return $this->view->render('register/email_register.twig');
    }

    private function messageMailReset($token, $username)
    {
        $url = $this->_helper->url->url(array(
            'module' => 'front',
            'controller'=>'register',
            'action'=>'change',
            'username'=>$username,
            'token'=>$token
            ));

        $this->view->name = $username;
        $this->view->changeLink = $url;
        
        return $this->view->render('register/email_reset.twig');
    }

    private function sendMail($mailTo, $subject, $message)
    {
        $mailTransport = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('transport');
//        $mailTransport = $this->getInvokeArg('bootstrap')->getResource('Transport');
//        Zend_Mail::setDefaultTransport($mailTransport);

        $mail = new Zend_Mail();
        $mail->addTo($mailTo);
        $mail->setSubject($subject);
        $mail->setBodyHtml($message);
        $mail->setFrom('duc.sutrix@gmail.com', 'Do Minh Duc');

        $mail->send($mailTransport);
    }    
}
